package com.cx.utils.rebooot;


import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @program: pms
 * @author: cx
 * @description: 机器人下发任务
 * @create: 2024-12-31 10:45
 **/
public class Reboot {
    // MySQL查询方法
    public String pySql(String ip, String sql) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 连接数据库
            String url = "jdbc:mysql://" + ip + ":3306/phoenix_rss";
            conn = DriverManager.getConnection(url, "root", "root123");
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            if (rs.next()) {
                return rs.getString(1); // 返回查询结果
            }
        } catch ( Exception e) {
            System.out.println("数据库出错: " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // AGV搬运任务提交
    public JSONObject agvCarry(String ip, String jobid, String rackTypeCode, String robotType, String startArea, String targetArea) {
        try {
            // 设置请求URL
            String url = "http://" + ip + "/api/rss/carrier/warehouse/1/transport-order/submit";
            Map<String, Object> data = new HashMap<>();
            data.put("awaitArea", "");
            data.put("businessType", "");
            data.put("calibrateCode", 0);
            data.put("checkCode", 0);
            data.put("deadline", "");
            data.put("endSlotGroup", "");
            data.put("endSlotType", "");
            data.put("isRobotRelay", "false");
            data.put("jobPriority", 1);
            data.put("letDownFlag", 2);
            data.put("lockTime", "");
            data.put("needOperation", "false");
            data.put("needOut", 1);
            data.put("needReset", "false");
            data.put("orderNo", "");
            data.put("orderType", "1");
            data.put("rackCode", "");
            data.put("rackTypeCode", rackTypeCode);
            data.put("remark", "");
            data.put("robotCode", robotType);
            data.put("robotEndPoint", "");
            data.put("robotPointName", "");
            data.put("robotType", "");
            data.put("sequence", 0);
            data.put("source", "");
            data.put("startArea", startArea);
            data.put("startPoint", startArea);
            data.put("targetArea", targetArea);
            data.put("targetPoint", targetArea);
            data.put("upOrderType", "1");
            data.put("upstreamOrderGroup", "");
            data.put("upstreamOrderNo", jobid);
            data.put("warehouseId", 1);
            data.put("workHeading", "");
            data.put("zoneCode", "kckq");

            // 发送POST请求
            String jsonResponse = sendPostRequest(url, new JSONObject(data).toString());

            return new JSONObject(Boolean.parseBoolean(jsonResponse)); // 返回响应的JSON对象
        } catch (Exception e) {
            System.out.println("调用接口失败: " + e.getMessage());
        }
        return null;
    }

    // 发送POST请求的辅助方法
    private String sendPostRequest(String url, String data) throws IOException, IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.getOutputStream().write(data.getBytes("UTF-8"));
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString(); // 返回响应内容
    }

    // MySQL任务状态查询方法
    public String mysqlSql(String ip, String jobid) {
        String sql = "SELECT order_state FROM transport_order WHERE upstream_order_no='" + jobid + "'";
        while (true) {
            try {
                Thread.sleep(2000); // 每2秒查询一次
                String state = pySql(ip, sql);
                if ("COMPLETED".equals(state)) {
                    return state;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 搬运任务主方法
    public  String carryOut(String ip, String jobid, String rackTypeCode, String robotType, String startArea, String targetArea) {
        try {
            JSONObject carryResult = agvCarry(ip, jobid, rackTypeCode, robotType, startArea, targetArea);
            System.out.println("货架搬运: " + carryResult);
            if (carryResult != null && carryResult.getBoolean("success")) {
                String sql = mysqlSql(ip, jobid);
                System.out.println("任务状态: " + sql + "，任务完成！");
                if ("COMPLETED".equals(sql)) {
                    return sql;
                } else {
                    System.out.println("状态错误");
                }
            } else {
                System.out.println("任务下发失败");
            }
        } catch (Exception e) {
            System.out.println("carryOut代码调用错误: " + e.getMessage());
        }
        return null;
    }

//    public static void main(String[] args) {
//        AGVTaskHandler taskHandler = new AGVTaskHandler();
//        String ip = "172.31.239.239";
//        String jobid = "12345";
//        String rackTypeCode = "MXG";
//        String robotType = "Robot_3";
//        String startArea = "0194";
//        String targetArea = "0264";
//
//        String result = taskHandler.carryOut(ip, jobid, rackTypeCode, robotType, startArea, targetArea);
//        System.out.println("任务结果: " + result);
//    }


//    public static void main(String[] args) {
//        CarryOne carryOne = new CarryOne();
//        String ip = "172.31.239.239";
//        String rackTypeCode = "MXG";  // 货架1
//        String robotType = "Robot_3";  // 小车
//        String loading = "0194";  // 点位2
//        String S102120_2 = "0264";  // 点位2
//        int num = 1000;
//
//        // 执行 carry_one 方法
//        carryOne.carryOne(ip, rackTypeCode, robotType, loading, S102120_2, num);
//    }
//
//    public void carryOne(String ip, String rackTypeCode, String robotType, String S100150_1, String S100150_2, int num) {
//        try {
//            for (int i = 0; i < num; i++) {
//                // 模拟休眠2秒
//                TimeUnit.SECONDS.sleep(2);
//
//                // 生成一个10位的 jobid
//                String jobid = generateJobId();
//
//                // 调用 carry_out 方法进行搬运操作
//                String car = carryOut(ip, jobid, rackTypeCode, robotType, S100150_1, S100150_2);
//                System.out.println("S100150_1 ------ > S100150_2搬运完成");
//
//                // 模拟休眠3秒
//                TimeUnit.SECONDS.sleep(3);
//
//                if ("COMPLETED".equals(car)) {
//                    // 第二次搬运操作
//                    TimeUnit.SECONDS.sleep(3);
//                    String car1 = carryOut(ip, jobid + "1", rackTypeCode, robotType, S100150_2, S100150_1);
//                    System.out.println("S100150_2 ------ > S100150_1搬运完成");
//
//                    if ("COMPLETED".equals(car1)) {
//                        TimeUnit.SECONDS.sleep(3);
//                    } else {
//                        System.out.println("100150任务状态获取失败");
//                    }
//                } else {
//                    System.out.println("100150任务下发失败");
//                }
//
//                // 打印执行次数
//                System.out.println("SVT100150货架任务执行次数：" + (i + 1));
//            }
//        } catch (InterruptedException e) {
//            System.out.println("carry_one代码调用错误：" + e.getMessage());
//        }
//    }
//
//    // 模拟 carry_out 方法
//    public String carryOut(String ip, String jobid, String rackTypeCode, String robotType, String from, String to) {
//        // 这里可以根据实际的业务逻辑实现
//        // 返回 "COMPLETED" 表示任务完成
//        return "COMPLETED";
//    }

    // 生成一个 10 位的 jobid
    private String generateJobId() {
        Random random = new Random();
        StringBuilder jobid = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            jobid.append(random.nextInt(9) + 1);  // 生成 1-9 的随机数
        }
        return jobid.toString();
    }
}

